import 'dart:async';
import 'dart:convert' as convert;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/model/device_upgrade_model.dart';
import 'package:wch/model/patient_label_list.dart';
import 'package:wch/model/patient_list.dart';
import 'package:wch/page/delete_user.dart';
import 'package:wch/page/delivery_device.dart';
import 'package:wch/page/new_user.dart';
import 'package:wch/page/user_detail.dart';
import 'package:wch/page/wifi_sest.dart';
import 'package:wch/utils/color_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/time_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/recycle_device_alert.dart';
import 'package:wch/widget/text_widget.dart';
import 'package:wch/utils/loading_utils.dart';

import '../constant/config_constant.dart';
import '../constant/event_bus_global.dart';
import '../constant/mqtt_constant.dart';
import '../helper/mqtt.dart';
import '../helper/preferences_helper.dart';
import '../model/acquisition_entity.dart';
import '../model/deviceInfo.dart';
import '../model/patient_device_list_entity.dart';
import '../model/patient_info_custom.dart';
import '../model/patient_label.dart';
import '../model/recycle_device_model.dart';
import '../native/net_business.dart';
import '../utils/log_utils.dart';
import '../utils/text_utils.dart';

class UserManagerPage extends StatefulWidget {
  const UserManagerPage({super.key});

  @override
  State<UserManagerPage> createState() => _UserManagerPageState();
}

class _UserManagerPageState extends State<UserManagerPage>{
  FocusNode focusNode = FocusNode();

  TextEditingController controller = TextEditingController();

  List<double> flagsHeight = [];

  List<Widget> allWidget = [];

  int userCount = 0;

  PatientListModel patientListEntity = PatientListModel();

  ///全部标签
  PatientLabelModel patientLabelList = PatientLabelModel();

  OverlayEntry? entry;

  RefreshController _refreshController = RefreshController(initialRefresh: false);
  ///订阅设备回收主题
  String? topic;
  ///发布的消息主题
  String? publicTopic;
  ///发布的主题消息类型
  Map<String, dynamic> topicMsg = {};
  ///当前选择的设备
  String? curDeviceId;
  ///页码
  int page = 1;
  bool noMoreData = false;
  bool isSearchMode = false;
  String? recycleTime;
  String? recycleRemark;
  StreamSubscription? deviceInfoSubscription;
  StreamSubscription? refreshSubscription;
  StreamSubscription? recycleSubscription;

  Timer? queryTimer;
  Timer? recycleTimer;

  @override
  void dispose() {
    super.dispose();
    deviceInfoSubscription?.cancel();
    refreshSubscription?.cancel();
    recycleSubscription?.cancel();
  }

  @override
  void initState() {

    refreshSubscription = globalEventBus.on<EventBufRefreshModel>().listen((event) {
      _onRefresh();
    });
    // globalEventBus.on<RecycleDeviceModel>().listen((event) {
    //   mqttCancelSubscribe(topic!);
    //   if (event.result) {
    //     NetBusiness().unbindDevice(curDeviceId!, recycleTime!, recycleRemark!).then((onValue){
    //       ToastUtils.showToast(msg: '设备回收成功');
    //       _onRefresh();
    //       mqttPublicMsg(publicTopic!, convert.jsonEncode(topicMsg));
    //     });
    //   } else {
    //     ToastUtils.showToast(msg: '无法回收设备');
    //     mqttCancelSubscribe(topic!);
    //   }
    // });

    // deviceInfoSubscription = globalEventBus.on<DeviceInfoModel>().listen((onData) {
    //   Loading.getIns().hide();
    //   if (onData.aioWorkStatus == 'Y') {
    //     ToastUtils.showToast(msg: '终端正在工作中，暂时不能回收');
    //     return;
    //   }
      // NetBusiness()
      //     .unbindDevice(curDeviceId!, recycleTime!, recycleRemark)
      //     .then((onValue) {
      //   if (onValue) {
      //     ToastUtils.showToast(msg: '设备回收成功');
      //
      //     ///刷新界面
      //     NetBusiness().patientDeviceList(widget.patientInfoCustom.userId).then((onValue) {
      //       setState(() {
      //         deviceListEntity = onValue;
      //       });
      //     });
      //
      //     ///mqtt 通知一体机
      //     Map<String, dynamic> msg = {};
      //     msg['messageType'] = mqttRecycleDevice;
      //     msg['data'] = {
      //       'token': PreferencesHelper.getUserToken(),
      //       'sickPersonId': widget.patientInfoCustom.userId!
      //     };
      //
      //     mqttPublicMsg('RL/SAAS/$curDeviceName/APP', convert.jsonEncode(msg));
      //   }
      // });
    // });

    controller.addListener(() {
      setState(() {
        controller.text;
        isSearchMode = controller.text.isNotEmpty;
      });
    });

    NetBusiness().patientAllLabel().then((value) {
      patientLabelList = value;
    });

    initData();

  }

  void initData() {
    NetBusiness().patientList(page, controller.text).then((value) {
      if (patientListEntity.data == null) {
        patientListEntity = value;
      } else {
        patientListEntity.data!.data!.addAll(value.data!.data!);
      }
      if (value.data!.data!.length < 10) {
        noMoreData = true;
      }

      setState(() {
        List<Widget> addedWidget = _getAllItem(value);
        allWidget.addAll(addedWidget);
      });
      userCount = allWidget.length - 1;
    });
  }

  void _onRefresh() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    NetBusiness().patientList(page, controller.text).then((value) {
      patientListEntity = value;
      if (value.data!.data!.length < 10) {
        noMoreData = true;
      } else {
        noMoreData = false;
        _refreshController.resetNoData();
      }
      setState(() {
        allWidget.clear();
        flagsHeight.clear();
        List<Widget> addedWidget = [];
        userCount = 0;
        if (!isSearchMode) {
          addedWidget = _getAllItem(value);
          allWidget.addAll(addedWidget);
          userCount = allWidget.length - 1;
        } else {
          addedWidget = _getAllItem2(value);
          allWidget.addAll(addedWidget);
          userCount = allWidget.length;
        }
      });
      _refreshController.refreshCompleted();
    });
  }

  void _onLoading() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // // if failed,use loadFailed(),if no data return,use LoadNodata()
    // // items.add((items.length+1).toString());
    // if(mounted)
    //   setState(() {
    //
    //   });
    // _refreshController.loadComplete();
    if (noMoreData) {
      _refreshController.loadNoData();
      return;
    }
    page ++;
    NetBusiness().patientList(page, controller.text).then((value) {
      if (patientListEntity.data == null) {
        patientListEntity = value;
      } else {
        patientListEntity.data!.data!.addAll(value.data!.data!);
      }
      if (value.data!.data!.length < 10) {
        noMoreData = true;
      }
      setState(() {
        // userCount = 0;
        if (!isSearchMode) {
          allWidget.addAll(_getAllItem(value));
          userCount = allWidget.length - 1;
        } else {
          allWidget.addAll(_getAllItem2(value));
          userCount = allWidget.length;
        }
      });
      _refreshController.loadComplete();
    });
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      title: '用户管理',
      rightBtn: GestureDetector(
        onTap: (){
          if (!isNetworking) {
            ToastUtils.showToast(msg: '网络不可用');
            return;
          }
          NavigatorUtil.push(context, DeleteUserPage(flagsHeight: flagsHeight, patientListEntity: patientListEntity,));
        },
        child: Container(
          padding: EdgeInsets.all(15),
          child:F14TitleText('删除', color: themeColor,)
          ,
        ),
      ),
      body: Stack(children: [
        UserManagerContainer(
          top:62.h,
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            footer: CustomFooter(
              builder: (context,mode){
                LogUtils.log('mode1=$mode');
                Widget body ;
                if(mode==LoadStatus.idle){
                  body =  Text("上拉加载");
                }
                else if(mode==LoadStatus.loading){
                  body =  CupertinoActivityIndicator();
                }
                else if(mode == LoadStatus.failed){
                  body = Text("加载失败！点击重试！");
                }
                else if(mode == LoadStatus.canLoading){
                  body = Text("松手,加载更多!");
                }
                else{
                  body = Text("没有更多数据了!");
                }
                return Container(
                  height: 55.0,
                  child: Center(child:body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            header: CustomHeader(builder: (context, mode) {
              LogUtils.log('mode2=$mode');
              Widget body = Container();
              if(mode==RefreshStatus.idle){
                body =  Text("下拉刷新");
              }
              else if(mode==RefreshStatus.refreshing){
                body =  CupertinoActivityIndicator();
              }
              else if(mode == RefreshStatus.failed){
                body = Text("刷新失败！请稍后重试！");
              }
              else if(mode == RefreshStatus.canRefresh){
                body = Text("松手,立即刷新!");
              }
              else if(mode == RefreshStatus.completed){
                body = Text("刷新完成!");
              }
              return Container(
                height: 55.0,
                child: Center(child:body),
              );
            },

            ),
            child: WaterfallFlow.builder(gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 10.0,
              lastChildLayoutTypeBuilder: (index) {
                if (index == allWidget.length) {
                  return LastChildLayoutType.foot;
                } else {
                  return LastChildLayoutType.none;
                }
              },
            ), itemBuilder: (ctx, id){
              return allWidget[id];
            }, itemCount: allWidget.length,),
          ),
        ),
        Positioned(
          child: Offstage(
            offstage: false,
            child: Column(
              children: [
                Container(
                  height: 35.h,
                  margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(17.5.h)),
                      border: Border.all(color: themeColor, width: 0.5.w)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      HorPadding(15.w),
                      Image.asset(
                        searchUserIcon,
                        width: 13.w,
                        height: 13.w,
                      ),
                      HorPadding(5.w),
                      Container(
                        width: ScreenUtil().screenWidth-120,
                        child: CupertinoTextField(
                          onSubmitted: (text) {
                            isSearchMode = controller.text.isNotEmpty;
                            focusNode.unfocus();
                            // setState(() {
                            //   allWidget.clear();
                            // });
                            _refreshController.requestRefresh();
                          },
                          focusNode: focusNode,
                          controller: controller,
                          decoration:
                              const BoxDecoration(color: Colors.transparent),
                          placeholder: '姓名、手机号码…',
                          placeholderStyle:
                              TextStyle(fontSize: 13.w, color: F1TextColor),
                          style: TextStyle(fontSize: 13.w, color: F1TextColor),
                          maxLines: 1,
                          maxLength: 11,
                        ),
                      ),
                      Expanded(child: Container()),
                      Visibility(
                        visible: controller.text.isNotEmpty,
                        child: GestureDetector(
                          onTap: (){
                            controller.clear();
                          },
                          child: Container(
                            padding: EdgeInsets.all(10.w),
                            child: Image.asset(fieldClearIcon, width: 14.w, height: 14.w,),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        Positioned(
            width: 200,
            //设置一个数值占位
            height: 100.h,
            left: ScreenUtil().screenWidth / 2 - 100,
            top: 170,
            child: Visibility(
              maintainInteractivity: false,
              visible: allWidget.isEmpty && controller.text.isNotEmpty,
              child: Container(
                height: 100.h,
                child: Column(
                  children: [
                    Image.asset(
                      searchEmptyPng,
                      width: 71.w,
                      height: 52.h,
                    ),
                    VerPadding(15.h),
                    F12TitleText(controller.text.isEmpty ? '暂无用户数据' : '没有“${controller.text}”相关内容',
                        color: contentTextColor),
                  ],
                ),
              ),
            ))
      ]),
    );
  }

  // List<Widget> _searchUser(String searchWord) {
  //   LogUtils.log('searchWord=$searchWord');
  //   List<Widget> all = [];
  //
  //   if (searchWord == '') {
  //     all.add(_getAddItem());
  //     for (int i = 0; i < patientListEntity.data!.data!.length; i++) {
  //       PatientListDataData data = patientListEntity.data!.data![i];
  //
  //       String? name;
  //       String? mobile;
  //       String? sex;
  //       String? date;
  //       String? deviceId = data.deviceId;
  //       String? deviceNumber = data.deviceNumber;
  //       String? deviceBluetoothNumber = data.deviceBluetoothNumber;
  //       String? createTime = data.createTime;
  //       String? doctor = data.doctorName;
  //       int? age;
  //       for(int j = 0; j < data.list!.length; j ++) {
  //         PatientListDataDataList user = data.list![j];
  //         if (user.name == '姓名') {
  //           if (user.text!.contains(searchWord)) {
  //             name = user.text;
  //           }
  //         } else if (user.name == '性别') {
  //           sex = user.text;
  //         } else if (user.name == '手机号') {
  //           mobile = user.text;
  //         } else if (user.name == '出生日期') {
  //           date = user.text;
  //         } else if (user.name == '年龄') {
  //           age = (user.text != null && user.text!.isNotEmpty) ? int.parse(user.text!) : 0;
  //         }
  //       }
  //       if (name != null) {
  //         flagsHeight.add(0);
  //         all.add(_getUserItem(i, createTime, doctor, deviceId, deviceNumber, deviceBluetoothNumber, data.text!, sex, mobile, date, age, data.shopLabelList!));
  //       }
  //     }
  //
  //     return all;
  //   }
  //
  //   flagsHeight.clear();
  //   for (int i = 0; i < patientListEntity.data!.data!.length; i++) {
  //     PatientListDataData data = patientListEntity.data!.data![i];
  //     String? name;
  //     String? mobile;
  //     String? sex;
  //     String? date;
  //     String? deviceId = data.deviceId;
  //     String? deviceNumber = data.deviceNumber;
  //     String? deviceBluetoothNumber = data.deviceBluetoothNumber;
  //     String? createTime = data.createTime;
  //     String? doctor = data.doctorName;
  //     int? age;
  //     for(int j = 0; j < data.list!.length; j ++) {
  //       PatientListDataDataList user = data.list![j];
  //       if (user.name == '姓名') {
  //         if (user.text!.contains(searchWord)) {
  //           name = user.text;
  //         }
  //       } else if (user.name == '性别') {
  //         sex = user.text;
  //       } else if (user.name == '手机号') {
  //         mobile = user.text;
  //       } else if (user.name == '出生日期') {
  //         date = user.text;
  //       } else if (user.name == '年龄') {
  //         age = (user.text != null && user.text!.isNotEmpty) ? int.parse(user.text!) : 0;
  //       }
  //     }
  //     if (name != null) {
  //       flagsHeight.add(0);
  //       all.add(_getUserItem(i, createTime, doctor, deviceId, deviceNumber, deviceBluetoothNumber, data.text!, sex, mobile, date, age, data.shopLabelList!));
  //     }
  //
  //   }
  //   return all;
  // }

  List<Widget> _getAllItem(PatientListModel patientList) {
    List<Widget> all = [];
    if (allWidget.isEmpty) {
      all.add(_getAddItem());
    }
    for (int i = 0; i < patientList.data!.data!.length; i++) {
      PatientListDataData data = patientList.data!.data![i];
      String? name;
      String? mobile;
      String? sex;
      String? date;
      String? deviceId = data.deviceId;
      String? deviceNumber = data.deviceNumber;
      String? deviceBluetoothNumber = data.deviceBluetoothNumber;
      String? createTime = data.createTime;
      String? doctor = data.doctorName;
      String? id = data.id;
      int? age;
      for(int j = 0; j < data.list!.length; j ++) {
        PatientListDataDataList user = data.list![j];
        if (user.name == '姓名') {
          name = user.text;
        } else if (user.name == '性别') {
          sex = user.text;
        } else if (user.name == '手机号') {
          mobile = user.text;
        } else if (user.name == '出生日期') {
          date = user.text;
          LogUtils.log('date=$date');
          age = TimeUtils.calculateAge(date!);
          LogUtils.log('age=$age');
        }
        // else if (user.name == '年龄') {
        //   age = (user.text != null && user.text!.isNotEmpty) ? int.parse(user.text!) : 0;
        // }
      }
      flagsHeight.add(0);
      all.add(_getUserItem(userCount + i, i, id!, createTime, doctor, deviceId, deviceNumber, deviceBluetoothNumber, name, sex, mobile, date, age, data.shopLabelList, data.acquisitionLabelList));
    }
    return all;
  }
  ///不带添加按钮
  List<Widget> _getAllItem2(PatientListModel patientList) {
    List<Widget> all = [];
    for (int i = 0; i < patientList.data!.data!.length; i++) {
      PatientListDataData data = patientList.data!.data![i];
      String? name;
      String? mobile;
      String? sex;
      String? date;
      String? deviceId = data.deviceId;
      String? deviceNumber = data.deviceNumber;
      String? deviceBluetoothNumber = data.deviceBluetoothNumber;
      String? createTime = data.createTime;
      String? doctor = data.doctorName;
      String? id = data.id;
      int? age;
      for(int j = 0; j < data.list!.length; j ++) {
        PatientListDataDataList user = data.list![j];
        if (user.name == '姓名') {
          name = user.text;
        } else if (user.name == '性别') {
          sex = user.text;
        } else if (user.name == '手机号') {
          mobile = user.text;
        } else if (user.name == '出生日期') {
          date = user.text;
        } else if (user.name == '年龄') {
          age = (user.text != null && user.text!.isNotEmpty) ? int.parse(user.text!) : 0;
        }
      }
      flagsHeight.add(0);

      all.add(_getUserItem(userCount + i, i, id!, createTime, doctor, deviceId, deviceNumber, deviceBluetoothNumber, name, sex, mobile, date, age, data.shopLabelList, data.acquisitionLabelList));
    }
    return all;
  }

  Widget _getAddItem() {
    return GestureDetector(
      onTap: (){
        NavigatorUtil.push(context, NewUserPage());
      },
      child: Container(
        height: 150.h,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
          color: Colors.white,
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              addUserIcon,
              width: 20.w,
              height: 20.w,
            ),
            VerPadding(7.5.h),
            F14TitleText('新增用户', color: F1TextColor),
          ],
        ),
      ),
    );
  }

  String showName(String? name) {
    if (name == null || name.isEmpty) {
      return '';
    }
    if (name.length > 4) {
      return '${name.substring(0, 3)}...';
    } else {
      return name;
    }
  }

  Widget _getUserItem(int index, int index2, String sickPersonId, String? createTime, String? doctor, String? deviceId, String? deviceNumber, String? deviceBluetoothNumber, String? name, String? sex, String? mobile, String? date, int? age, List<PatientLabelListShopLabelList>? labelList, List<AcquisitionAcquisitionLabelList>? acqLabelList) {
    
    LogUtils.log('index=$index');
    LogUtils.log('index2=$index2');
    List<Widget> widgets = [];
    if (labelList != null && labelList.isNotEmpty) {
      widgets = _getDoctorWidget(index2, labelList);
    }

    double mobileHeight = mobile == null ? 0 : 15.h;
    double dateHeight = date == null ? 0 : 15.h;

    return GestureDetector(
      onTap: (){
        PatientInfoCustom model = PatientInfoCustom(name: name!, sex: sex ?? '男', age: age ?? 0, userId: patientListEntity.data!.data![index].id!, mobile: mobile);
        NavigatorUtil.push(context, UserDetailPage(patientInfoCustom:model, labelModel: patientLabelList, labelList: acqLabelList));
      },
      child: Container(
        height: 105.h + flagsHeight[index2] + mobileHeight + dateHeight,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(7.5.h)),
          color: Colors.white
        ),
        child: ConstraintLayout(
          children: [
            Image.asset(
              sex == '男' ? patientMaleImg : patientFemaleImg,
              width: 23.w,
              height: 23.w,
            ).applyConstraint(
                left: parent.left.margin(15.w),
                top: parent.top.margin(23.h),
                size: 23.w),
            BoldText(
              showName(name),
              fontSize: 15,
            ).applyConstraint(
                left: rId(0).right.margin(5.w),
                top: rId(0).top,
                maxHeight: 30.h),
            Image.asset(
              sex == '男' ? hospitalMaleIcon : hospitalFemaleIcon,
              width: 10.w,
              height: 10.w,
            ).applyConstraint(
                left: rId(1).right.margin(5.w),
                centerVerticalTo: rId(0),
                size: 10.w),
            GestureDetector(
              onTap: () async {
                if (deviceId == null) {
                  PatientInfoCustom model = PatientInfoCustom(name: name!, sex: sex ?? '男', mobile: mobile, age: age ?? 0, userId: patientListEntity.data!.data![index].id!);
                  NavigatorUtil.push(context, DeliveryDevicePage(patientInfoCustom: model,labelList: acqLabelList ?? [],patientLabelModel: patientLabelList));
                } else {
                  PatientDeviceListEntity entity = await NetBusiness().patientDeviceList(sickPersonId);
                  String bmDeviceBluetoothNumber = entity.data!.data!.first.bmDeviceBluetoothNumber ?? '';
                  String deviceName = entity.data!.data!.first.deviceBluetoothNumber ?? '';
                  CustomRecycleMode model = CustomRecycleMode(entity.data!.data![0].createTime, deviceId, deviceNumber, bmDeviceBluetoothNumber, acqLabelList, doctor, '', '', deviceName);
                  entry = OverlayEntry(builder: (ctx) {
                    return RecycleDeviceAlert(
                      customRecycleMode: model,
                      entry: entry!, callback: (id, time, remark){
                        if (id == 1) {
                          recycleDevice(deviceId, deviceName, sickPersonId, time, remark);
                        }
                    },);
                  });
                  Overlay.of(context).insert(entry!);
                }

              },
              child: F12TitleText(deviceId != null ? deviceNumber == null ? '回收设备' : '回收设备($deviceNumber)' : '分配设备', color: deviceId != null ? Color(0xFFF78554) : themeColor)
            ).applyConstraint(
                bottom: parent.bottom.margin(0),
                left: parent.left,
                right: parent.right,
                height: 26.h),
            LineWidget(width: (ScreenUtil().screenWidth - 30.w) / 2, height: 0.5)
                .applyConstraint(
                    left: parent.left,
                    right: parent.right,
                    height: 0.5,
                    bottom: rId(3).top.margin(7.h)),
            F14TitleText(date ?? '', color: F1TextColor).applyConstraint(
                left: rId(1).left,
                right: parent.right,
                width: matchConstraint,
                height: date == null ? 0 : 15.h,
                top: rId(1).bottom.margin(3.h)),
            F14TitleText(mobile ?? '', color: F1TextColor).applyConstraint(
              left: rId(1).left,
              right: parent.right,
              width: matchConstraint,
              height: date == null ? 0 : 15.h,
              top: rId(5).bottom,
            ),
            GestureDetector(
                onTap: (){
                  ///创建标签组件数组
                  entry = OverlayEntry(builder: (ctx) {
                    // List<FlagModel> models = [FlagModel('1234444444444', false, Colors.red, Colors.green), FlagModel('2234', true), FlagModel('223', false)];

                    List<PatientAllLabelData>? labelData = patientLabelList.data;
                    if (labelData != null && labelData.isNotEmpty) {
                      for (int i = 0; i < labelData!.length; i ++) {
                        labelData[i].isChecked = false;
                      }
                      List<PatientLabelListShopLabelList>? patientShopLabelList = patientListEntity.data!.data![index].shopLabelList;
                      if (patientShopLabelList != null && patientShopLabelList.isNotEmpty) {
                        for (int i = 0; i < labelData!.length; i ++) {
                          for (int j = 0; j < patientShopLabelList!.length; j ++) {
                            PatientLabelListShopLabelList label = patientShopLabelList[j];
                            if (labelData[i].name == label.name) {
                              labelData[i].isChecked = true;
                            }
                          }
                        }
                      }
                    }

                    return EditFlagAlert(title: '修改采集标签', entry: entry!, flagModels: patientLabelList.data!, actionCallback: (List<PatientAllLabelData> labelList){
                      if (labelList.isEmpty){
                        return;
                      }
                      List<Map<String, String>> list = [];
                      for(int i = 0; i < labelList.length; i ++) {
                        PatientAllLabelData data = labelList[i];
                        if (data.isChecked) {
                          Map<String, String> m = <String, String>{};
                          m['id'] = data.id!;
                          list.add(m);
                        }
                      }

                      NetBusiness().patientAddLabel(patientListEntity.data!.data![index].id!, list).then((value) {
                        if (value) {
                          _onRefresh();
                        }
                      });

                    },);
                  });
                  Overlay.of(context).insert(entry!);
                },
                child: Offstage(
                  offstage: patientListEntity.data!.data![index2].shopLabelList == null || patientListEntity.data!.data![index2].shopLabelList!.isEmpty,
                  child: Image.asset(
                    editUserIcon,
                    width: 20.w,
                    height: 20.w,
                  ),
                )).applyConstraint(
              right: parent.right.margin(8.w),
              top: rId(6).bottom,
              clickPadding: EdgeInsets.all(10),
              size: 20.w,
            ),
            Container(
              child: Stack(
                children: widgets,
              ),
            ).applyConstraint(
                left: rId(1).left,
                right: rId(7).left,
                width: matchConstraint,
                top: rId(6).bottom.margin(5.h),
                height: flagsHeight[index2]),
            Offstage(
              child: Image.asset(patientCheckedIcon, width: 15.w, height: 15.w,),
            ).applyConstraint(
                size: 15.w,
                right: parent.right.margin(10.w),
                top: rId(1).top
            )
          ],
        ),
      ),
    );
  }

  List<Widget> _getDoctorWidget(int index, List<PatientLabelListShopLabelList> labelList) {
    // return Container(
    //   margin: EdgeInsets.symmetric(horizontal: 20.w),
    //   padding: EdgeInsets.all(10.w),
    //   child: ,
    // )
    double width = (ScreenUtil().screenWidth - 30.w) / 2 - 70.w;
    // List<String> flags = [];
    // for (int i = 0; i < labelList.length; i ++) {
    //   flags.add('骨科111');
    // }

    List<Widget> widgets = [Container()];

    flagsHeight[index] = 0;
    double posX = 0;
    for (int i = 0; i < labelList.length; i++) {
      Size size = _getTextSize(labelList[i].name!, (ScreenUtil().screenWidth - 30.w) / 2 - 70.w, 10);
      if (flagsHeight[index] == 0) {
        flagsHeight[index] = size.height + 5;
      }
      posX += size.width + 10;
      if (posX > width) {
        posX = size.width + 10;
        flagsHeight[index] += size.height + 10;
      }

      widgets.add(Positioned(
        left: posX - size.width - 10,
        top: flagsHeight[index] - size.height - 5,
        width: size.width + 10,
        height: size.height + 5,
        child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: ColorUtils.getColorFromHex(labelList[i].colour!).withOpacity(0.2),
              borderRadius: BorderRadius.all(Radius.circular(5.w))),
          child: F10TitleText(
            labelList[i].name!,
            color: ColorUtils.getColorFromHex(labelList[i].colour!),
          ),
        ),
      ));

      posX += 5;
    }

    if (widgets.length == 1) {
      flagsHeight[index] = 10;
    }

    return widgets;
  }

  Size _getTextSize(String text, double maxWidth, double fontSize) {
    TextStyle style = TextStyle(
      fontSize: fontSize,
    );
    return TextUtils.boundingTextSize(text, style,
        maxWidth: maxWidth);
  }

  ///回收设备逻辑
  void recycleDevice(String deviceId, String bluetoothName, String sickPersonId,
      String time, String remark) {
    curDeviceId = deviceId;
    deviceInfoSubscription =
        globalEventBus.on<DeviceInfoModel>().listen((onData) async {
      queryTimer?.cancel();
      mqttCancelSubscribe(topic!);
      deviceInfoSubscription!.cancel();
      if (onData.aioWifiStatus != 'Y') {
        entry = OverlayEntry(builder: (ctx) {
          return CommonAlert(
            title: '一体机断网',
            msg: '一体机Wi-Fi断开，请重连',
            callback: (id) {
              if (id == 1) {
                NavigatorUtil.push(context, WifiSetPage());
              }
            },
            entry: entry!,
            leftBtnText: '取消',
            rightBtnText: 'Wi-Fi连接',
          );
        });
        Overlay.of(context).insert(entry!);
        return;
      }

      globalEventBus.fire(EventBufRefreshModel());

      await Future.delayed(const Duration(seconds: 2));
      Loading.getIns().hide();

      ///mqtt 通知一体机
      Map<String, dynamic> msg = {};
      msg['messageType'] = mqttRecycleDevice;
      msg['data'] = {
        'token': PreferencesHelper.getUserToken(),
        'sickPersonId': sickPersonId
      };
      mqttPublicMsg('RL/SAAS/$bluetoothName/APP', convert.jsonEncode(msg));

      ///订阅
      mqttSubscribe('RL/SAAS/$bluetoothName');

      Loading.getIns().loading(msg: '正在回收设备');
      recycleTimer = Timer(Duration(seconds: 20), () {
        Loading.getIns().hide();
        mqttCancelSubscribe('RL/SAAS/$bluetoothName');
        recycleSubscription!.cancel();
      });
      recycleSubscription =
          globalEventBus.on<RecycleDeviceModel>().listen((recycleModel) {
            LogUtils.log('123456');
        ///取消订阅
        mqttCancelSubscribe('RL/SAAS/$bluetoothName');
        recycleSubscription!.cancel();
        recycleTimer?.cancel();
        Loading.getIns().hide();
        if (recycleModel.result) {
          NetBusiness().unbindDevice(deviceId, time, remark).then((onValue) {
            if (onValue) {
              ToastUtils.showToast(msg: '设备回收成功');

              ///刷新界面
              _onRefresh();
            }
          });
        } else {
          ToastUtils.showToast(msg: '设备回收失败');
        }
      });
    });

    curDeviceId = deviceId;
    topic = 'RL/SAAS/$bluetoothName';
    Loading.getIns().loading(msg: '正在查询终端状态');
    queryTimer = Timer(Duration(seconds: 20), () {
      Loading.getIns().hide();
      ToastUtils.showToast(msg: '查询终端状态超时');
    });

    mqttSubscribe(topic!);
    String pubTopic = 'RL/SAAS/$bluetoothName/APP';
    Map<String, dynamic> msg2 = {'messageType': mqttDeviceInfo};
    mqttPublicMsg(pubTopic, convert.jsonEncode(msg2));
  }

  // @override
  // void notify(String methodName, Map<dynamic, dynamic> data) {
  //   // TODO: implement notify
  //   if (methodName == eventBluetooth) {
  //     List<int> cmdList = data['cmd'];
  //     DecodeEntity decodeEntity = AIODecode.decodeData(cmdList);
  //     debugPrint('decodeEntity.name=${decodeEntity.name}');
  //     if (decodeEntity.name == 'aioInfo') {
  //       if (!decodeEntity.info['wifi_open'] || !decodeEntity.info['wifi_connected']) {
  //         entry = OverlayEntry(builder: (ctx){
  //           return CommonAlert(title: '一体机断网', msg: '一体机Wi-Fi断开，请重连', callback: (id){
  //             if (id == 1) {
  //               NavigatorUtil.push(context, WifiSetPage());
  //             }
  //           }, entry: entry!, leftBtnText: '取消', rightBtnText: 'Wi-Fi连接',);
  //         });
  //         Overlay.of(context).insert(entry!);
  //         EventManager.getIns().removeObserver(this);
  //       } else if (!decodeEntity.info['workStatus']){
  //         ToastUtils.showToast(msg: '终端正在工作中，暂时不能回收');
  //         EventManager.getIns().removeObserver(this);
  //       } else {
  //         ///查询额贴信息
  //         List<int> cmdList = [0xbb, 0x06, 0x00, 0x00, 0x00];
  //         NativeUtils.nativeAIOListener(cmdList);
  //       }
  //     } else if (decodeEntity.name == 'pasterInfo') {
  //       EventManager.getIns().removeObserver(this);
  //       if (decodeEntity.info['workStatus'].workStatus == 'Y') {
  //         ToastUtils.showToast(msg: '请将脑贴回仓后，再进行设备回收');
  //         return;
  //       } else {
  //         queryTimer?.cancel();
  //         mqttCancelSubscribe(topic!);
  //         deviceInfoSubscription!.cancel();
  //         Loading.getIns().hide();
  //
  //         NetBusiness()
  //             .unbindDevice(curDeviceId!, curTime!, curRemark!)
  //             .then((onValue) {
  //           if (onValue) {
  //             ToastUtils.showToast(msg: '设备回收成功');
  //             ///刷新界面
  //             _onRefresh();
  //
  //             globalEventBus.fire(EventBufRefreshModel());
  //             ///mqtt 通知一体机
  //             Map<String, dynamic> msg = {};
  //             msg['messageType'] = mqttRecycleDevice;
  //             msg['data'] = {
  //               'token': PreferencesHelper.getUserToken(),
  //               'sickPersonId': curSickPersonId
  //             };
  //             mqttPublicMsg('RL/SAAS/$curDeviceId/APP', convert.jsonEncode(msg));
  //           }
  //         });
  //       }
  //     }
  //   }
  // }

}

///公共父容器
class UserManagerContainer extends StatelessWidget {
  const UserManagerContainer({super.key, required this.child, required this.top});

  final Widget child;

  final double top;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 15.w, right: 15.w, top: top, bottom: 0),
      decoration: BoxDecoration(
          color: Color(0xFFF8F9FB), borderRadius: BorderRadius.circular(20.h)),
      child: child ?? Container(),
    );
  }
}

